<template>
  <div class="app-container">
    <!-- 搜索和 操作的行为区 -->
    <div class="conduct">
      <el-input v-model="listQuery.keyword" placeholder="查找账户" class="conduct-input">
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
      <el-button class="danger-btn" @click="handleUpdate(-1, 'create')">添加</el-button>
      <el-button class="primary-btn" @click="handleDelmultip">删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column label="平台名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.saasName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SaaSID" prop="id" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>{{ row.saasCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Access-Key" align="center" min-width="180px">
        <template slot-scope="{row}">
          <span>{{ row.accessKey }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Secret-Key" align="center" min-width="180px">
        <template slot-scope="{row}">
          <span>{{ row.secretKey }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="150">
        <template slot-scope="{row}">
          <el-switch
            v-model="row.status"
            active-color="#0F8CFD"
            inactive-color="#B0B7C9"
            active-text="正常"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus(row.saasCode, row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <span class="action action-update" @click="handleUpdate(row, 'updata')">修改</span>
          |
          <span class="action action-delete" @click="handleDelete(row,$index)">删除</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="平台设置" :visible.sync="dialogFormVisible" width="50%" center :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 600px; margin-left:50px;">
        <el-form-item label="平台名称:" prop="saasName">
          <el-input v-model="temp.saasName" type="text" maxlength="18" placeholder="请输入账户名" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='updata'" label="SaaSID:">
          <el-input v-model="temp.saasCode" disabled name="saasCode" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='updata'" label="Access-Key:" prop="accessKey">
          <el-input v-model="temp.accessKey" disabled name="accessKey" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='updata'" label="Secret-Key:" prop="secretKey">
          <el-input v-model="temp.secretKey" name="secretKey" disabled>
            <span slot="append" class="regeneration" @click="handleRegeneration()">
              重新生成
            </span>
          </el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-switch
            v-model="temp.status"
            active-color="#0F8CFD"
            inactive-color="#B0B7C9"
            active-text="正常"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button class="primary-btn" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <!-- 删除的提示框 -->
    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center :close-on-click-modal="false">
      <div class="del-data del-img"><img :src="require('../../assets/img/del.png')" alt=""></div>
      <div class="del-data del-notify">确定对账号进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="primary-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils' // 解析时间
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { delPlatform, addPlatform, editPlatform, listPlatform, togglePlatform, getAKSK } from '@/api/platform'
import { validPass, validPassKey, validPassId } from '@/utils/validate'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Platformlist',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const validatePasswordKey = (rule, value, callback) => {
      let len = 0
      if (typeof (value) !== 'undefined' && value != '') {
        len = value.length
      }
      if ((len < 32 || len > 36) && typeof (value) !== 'undefined' && value != '') {
        callback(new Error('为空系统生成  或填写32位,包含大小写字母和数字'))
      } else { callback() }
    }
    const validatePasswordId = (rule, value, callback) => {
      let len = 0
      if (typeof (value) !== 'undefined' && value != '') {
        len = value.length
      }
      if ((len < 23 || len > 28) && typeof (value) !== 'undefined' && value != '') {
        callback(new Error('为空系统生成  或填写24位,包含大小写字母和数字'))
      } else { callback() }
    }
    const validatePlatform = (rule, value, callback) => {
      if (value < 2 || value > 16) {
        callback(new Error('平台名称为2~16位'))
      } else { callback() }
    }

    return {
      multipleSelection: [],
      is_multip: false, // 是否批量删除
      tableKey: 0,
      list: null,
      total: 0, // 总条数
      listLoading: true,
      listQuery: {
        page: 1, // 第几页
        limit: 10, // 每页显示的条数row
        keyword: '' // 搜索关键字
      },
      calendarTypeOptions,
      temp: {
        accessKey: '',
        saasCode: '',
        saasName: '',
        secretKey: '',
        status: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      del_id: '',
      del_index: null,
      dialogPvVisible: false,
      rules: {
        accessKey: [{ required: false, trigger: 'blur', validator: validatePasswordKey }],
        secretKey: [{ required: false, trigger: 'blur', validator: validatePasswordKey }],
        saasCode: [{ required: false, trigger: 'blur', validator: validatePasswordId }],
        saasName: [{ required: true, trigger: 'blur', validator: validatePlatform }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取 table 列表
    getList() {
      this.listLoading = true
      listPlatform(this.listQuery.page, this.listQuery.limit, this.listQuery.keyword).then(res => {
        this.list = res.data.records
        this.total = parseInt(res.data.total)

        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      })
    },
    // 状态值 切换
    changeStatus(id, status) {
      togglePlatform(id, status).then(res => {
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 4000
        })
        // this.$message({
        //   message: "状态更改成功!",
        //   type: 'success',
        //   duration: 4000,
        //   showClose: true,
        //   center: true,
        // })
        this.getList() // 重新渲染页面
      })
    },
    // 点击了 '编辑' 或添加======================================================
    handleUpdate(row, str) {
      if (str == 'create') this.resetTemp() // 清空
      if (str == 'updata') this.temp = Object.assign({}, row) // 克隆一个对象
      this.dialogStatus = str
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑: 确认更新数据
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (typeof (this.temp.accessKey) === 'undefined') { this.temp.accessKey = '' }
          if (typeof (this.temp.secretKey) === 'undefined') { this.temp.secretKey = '' }
          if (typeof (this.temp.saasCode) === 'undefined') { this.temp.saasCode = '' }
          editPlatform(this.temp.saasName, this.temp.saasCode, this.temp.accessKey,
            this.temp.secretKey, this.temp.status).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
            this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 4000
            })
          })
        }
        else {
          return false;
        }
      })
    },
    // 确认添加了
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (typeof (this.temp.accessKey) === 'undefined') { this.temp.accessKey = '' }
          if (typeof (this.temp.secretKey) === 'undefined') { this.temp.secretKey = '' }
          if (typeof (this.temp.saasCode) === 'undefined') { this.temp.saasCode = '' }
          addPlatform(this.temp.saasName, 1).then(() => {
            this.getList()
            // this.list.unshift(this.temp)
            this
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 4000
            })
          })
        }
        else {
          return false;
        }
      })
    },
    // 清空temp
    resetTemp() {
      this.temp = {
        saasName: '',
        saasCode: '',
        accessKey: '',
        secretKey: '',
        status: 1
      }
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 修改时 重新生成 SK
    handleRegeneration() {
      getAKSK().then(res => {
        this.temp.secretKey = res.data.secretKey
      })
      // this.temp.secretKey = (Math.random() * 10000000).toString(16).substr(0, 4) + '-' + (new Date()).getTime() + '-' + Math.random().toString().substr(2, 5)
    },
    // 点击了删除=====================================================
    handleDelete(row, index) {
      this.is_multip = false
      this.del_id = row.id
      this.del_index = index
      this.dialogPvVisible = true
    },
    // 点击了 批量删除
    handleDelmultip() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '没有被选项!',
          type: 'error',
          duration: 4000,
          showClose: true,
          center: true
        })
      } else {
        this.is_multip = true
        this.dialogPvVisible = true
      }
    },
    // 确认了删除
    delData() {
      let ids = []
      if (this.is_multip) { // 批量删
        this.multipleSelection.forEach((item, i) => {
          ids.push(item.id)
        })
        // ids = this.multipleSelection
      } else {
        ids = [this.del_id]
      }
      delPlatform(ids).then(() => {
        this.dialogPvVisible = false
        // this.list.splice(this.del_index, 1)
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 4000
        })
      })
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    }

  }
}
</script>

<style lang="scss" scoped>
  $theme_text: #0F8BFD;
  $backg:rgba(0,0,0,0);
  $deep_text: #5E5E5E;
  $theme_red: #ff5357;

  .app-container {
    // background-color: #f99 !important;
    .conduct {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 9;
      width:50%;
      display: flex;
      justify-content: space-between;
      .conduct-input {
        margin-right: 10px;
        border: 0;
        input {
          background: transparent;
          border: 0;
          -webkit-appearance: none;
          border-radius: 0px;
          padding: 12px 5px 12px 15px;
          color: $deep_text;
          // height: 47px;
          caret-color: $deep_text;

          &:-webkit-autofill {
            box-shadow: 0 0 0 1000px $backg inset !important;
            -webkit-text-fill-color: $deep_text !important;
          }
        }
        .el-button {
          color: #fff;
          background-color: #0F8CFD;
        }
      }
    }

    // background-color: #f99 !important;
    .el-table {
      .action {
        cursor: pointer;
        &:hover {
          text-decoration: underline;
        }
      }
      .action-update {
        color: $theme_text;
      }
      .action-delete {
        color: $theme_red;
      }
    }
    .el-dialog {
      .regeneration {
        color: $theme_text;
        cursor: pointer;
      }
      .del-data {
        text-align: center;
        margin-bottom: 16px;
        img {
          width: 110px;
          height: 110px;
        }
      }
      .del-img {}
      // min-width: 490px !important;
      // .el-input {
      //   width: 100%;
      //   background-color: blueviolet;
      // }
    }
  }
</style>
